import { useEffect } from 'react';
import { openNotification_util, useCallbackState, fetchsync_util } from '../util/util.js'
import { UploadOutlined,DeleteOutlined} from '@ant-design/icons';
import { Upload, Button } from 'antd';
import fetch from 'isomorphic-fetch'

var storage = window.localStorage;

//预览图片用

const Upload_dgfj_hooks = (props) => {
	const [formdata, setFormData] = useCallbackState({ tpurl: "" });
	const [filelistobj, setFilelistobj] = useCallbackState(() => {
		var filelistinitarr = [];
		var tparr = props.initpxtpurl ? props.initpxtpurl.split(",") : []
		//若大于1说明是edit方法有初始图片。
		if (tparr.length >= 1 && tparr[0] != "") {
			tparr.map((item) => {
				if (item != "") {
					const url = "http://111.77.154.58:2233/" + item
					filelistinitarr.push({ uid: item, url: url, name: item })
				} else;
			})
		} else;
		let nowfilelistobj = Object.assign({}, filelistobj, { filelistitem: filelistinitarr });
		return nowfilelistobj
	});

	useEffect(() => {
		var filelistinitarr = [];
		var tparr = props.initpxtpurl === null?[]:props.initpxtpurl.split(",")
		//若大于1说明是edit方法有初始图片。
		if (tparr.length >= 1 && tparr[0] != "") {
			tparr.map((item) => {
				const url = "http://111.77.154.58:2233/" + item
				filelistinitarr.push({ uid: item, url: url, name: item })
			})
		} else;
		let nowfilelistobj = Object.assign({}, filelistobj, { filelistitem: filelistinitarr });
		setFilelistobj(nowfilelistobj)

	}, [props.initpxtpurl]);

	///通用上传单文件 重新改用单文件上传,新写法，解耦file与预览file列表
	const handleupload_beforeupload = (file, filelistname, key, text) => {
		uploadimggetutl(file, filelistname, key, text)
		return false;
	};

	//通用附件上传方法
	const uploadimggetutl = (file, filelistname, key) => {
		const formData = new FormData();
		formData.append('files[]', file);
		fetch("/admin/common/uploadfs", {
			method: 'POST', mode: 'cors', credentials: 'include', body: formData,
			headers: { 'Authorization': `Bearer ${storage.token}` }
		}).then(response => {
			if (response.status == '4x0x1') { openNotification_util("权限认证过期，重新登陆！") } else
				return response.text();
		}).then(data => {
			data=JSON.parse(data);
			//返回的是保存好的文件名，还要拼接地址
			var url = "http://111.77.154.58:2233/" + data.filename
			var fileobj = { uid: data.filename, url: url, name: data.filename }
			var prevfilelist = filelistobj[filelistname];
			console.log(prevfilelist);
			let nowfilelistobj = Object.assign({}, filelistobj, { [filelistname]: [ fileobj] });
			setFilelistobj(nowfilelistobj, () => {
				let tpurl = "";
				nowfilelistobj[filelistname].map((item, index) => {
					tpurl = index == 0 ? item.name + tpurl : item.name + "," + tpurl
				});
				let nowformdata = Object.assign({}, formdata, { [key]: tpurl });
				setFormData(nowformdata, () => {
					props.handleback(tpurl);
				})

			})
		});
	};

	//通用上传移除多文件，重构，改写原来单文件的移除方法·。
	const handleupload_beforeonremove_muti = (file, filelistname, key) => {
		var list = filelistobj[filelistname];
		const index = list.indexOf(file);
		const newFileList = list.slice();
		newFileList.splice(index, 1);
		let nowfilelistobj = Object.assign({}, filelistobj, { [filelistname]: newFileList });
		let tpurl = "";
		newFileList.map((item, index) => {
			tpurl = index == 0 ? item.name + tpurl : item.name + "," + tpurl
		});
		let nowformdata = Object.assign({}, formdata, { [key]: tpurl });
		setFormData(nowformdata, () => {
			setFilelistobj(nowfilelistobj, () => {
				props.handleback(tpurl);
			})
		})
		fetchsync_util("/admin/common/deleteFile", "DELETE", { file: file.name }, "text")
	}

	//取消预览
	//预览
	const handlePreview = async (file) => {
		console.log(file);
		var protocol = window.location.protocol;  
		var hostname = window.location.hostname;
		var port = window.location.port;
		let url=`${protocol}//${hostname}:${port}/${file.name}`
		console.log(url);
		window.open(url,"_blank");
		
		//删除了部分无用代码
	};

	//console.log("子组件触发")
	return (
		<div style={{  textAlign: "left", backgrounColor: "red",position:'relative',overflowY:"auto",scrollbarWidth:"10px",
		height:props.style?.height?props.style.height:filelistobj.filelistitem.length>0?
		((filelistobj.filelistitem.length-1)*1.1+1.6+"rem"):"100%"}}>
			<Upload listType='text'
			    name='file'
				maxCount={1}
				accept='.pdf,image/*,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt'
				beforeUpload={(file) => handleupload_beforeupload(file, 'filelistitem', 'tpurl', '文本')}
				fileList={filelistobj.filelistitem}
				onRemove={(file) => handleupload_beforeonremove_muti(file, 'filelistitem', 'tpurl')}
				onPreview={handlePreview}
				itemRender={(originNode, file) => (
					<div style={{marginLeft:"0.2rem",display: 'flex', justifyContent: 'flex-start', alignItems: 'center', width: '100%'}}>
						<div style={{color: "#a91f24", fontSize:"12px",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}} 
							onClick={()=>handlePreview(file)}>
							{file.name.split("-")[1]}
						</div>
						<Button 
							type="link" 
							danger
							size="small"
							onClick={() => handleupload_beforeonremove_muti(file, 'filelistitem', 'tpurl')}>
							<DeleteOutlined/>
						</Button>
					</div>
				)}
				// className="ant-upload-list-text .ant-upload-list-item-namered"
			>  <div ><Button style={{fontSize:"11px",fontWeight:"800",color:"#a91f24"}} 
			icon={<UploadOutlined />}>上传</Button></div> </Upload>
			
			{/* <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
				<img
					alt="example"
					style={{
						width: '100%',
					}}
					src={previewImage}
				/>
			</Modal> */}
		</div>
	);
};

export default Upload_dgfj_hooks;

//通用附件上传方法多图
//删除了部分无用代码

// //通用上传多文件
// 删除了部分无用代码